import axios from 'axios';
import { message } from "antd";
import { REU_ROOT, MAX_COUNT, SUCCESS_RES, MAX_COMMENT_COUNT } from './config';
import clientAxiosInstance from '../request';

export const gotoBlogContentPageUrl = (blogId) => `/content.html?blogId=${blogId}`;

export const GET_BLOG_LIST_URL = (curPage, count, label = '') => (
    `${REU_ROOT}/editor/getBlogList?curPage=${curPage}&count=${count}&label=${label}`
);

export const GET_NEW_COMMENTS_URL = (curPage, count) => (
    `${REU_ROOT}/comment/newComments?curPage=${curPage}&count=${count}`
);

export const GET_BLOG_LABELS_URL = () => `${REU_ROOT}/editor/labelCount`;

export const GET_BLOG_COMMENTS = (blogId) => `${REU_ROOT}/comment/blogComment?blogId=${blogId}`;

export const POST_BLOG_COMMENT = () => `${REU_ROOT}/comment/insert`;

export const GET_BLOG_CONTENT_URL = (blogId) => `${REU_ROOT}/editor/blogContent?blogId=${blogId}`;

export const GET_NEXT_AND_PREV_URL = (createTime) => `${REU_ROOT}/editor/nextAndPrev?createTime=${createTime}`;

export const GET_AUTHOR_INFO_URL = () => `${REU_ROOT}/admin/adminInfo`;

export function defaultFailReq() {
    message.error({ content: "服务器发生错误>_<" });
}

export function consoleErr(err) {
    console.error(err);
}

export function requestFn(
    reqFn,
    fnArgs,
    success,
    fail = defaultFailReq,
    catchErr = consoleErr,
) {
    const p = fnArgs.length ? reqFn(...fnArgs) : reqFn();
    p.then((res) => {
        const { data } = res;
        if (data.code === SUCCESS_RES) {
            success(data.data);
        } else {
            fail(data);
        }
    }).catch((err) => {
        catchErr(err);
    });
}

export function getBlogList(curPage, count = MAX_COUNT, label, axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_BLOG_LIST_URL(curPage, count, label));
}

export function getNewComments(curPage = 0, count = MAX_COMMENT_COUNT, axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_NEW_COMMENTS_URL(curPage, count));
}

export function getBlogContent(blogId, axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_BLOG_CONTENT_URL(blogId));
}

export function getBlogLabels(axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_BLOG_LABELS_URL());
}

export function getBlogComments(blogId, axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_BLOG_COMMENTS(blogId));
}
export function postBlogComment(commentInfo) {
    return axios.post(POST_BLOG_COMMENT(), commentInfo);
}

export function getNextAndPrevBlog(createTime) {
    return axios.get(GET_NEXT_AND_PREV_URL(createTime));
}

export function getAuthorInfo(axiosInstance = clientAxiosInstance) {
    return axiosInstance.get(GET_AUTHOR_INFO_URL());
}
